謝謝 timmy890710 的留言,
在DAY16-含金量滿滿的文章? Step(4/4):關鍵分點的籌碼資訊,你也可以自己拿!
時隔幾個月沒碰,需要把 chromedriver 更新一下,
有關於您提出的這個問題:如何修改成取得"期間累積買賣超張數"的數值
概念很簡單,觀察一下網頁元素的規律:
我們要的值 -2 被包在<font></font>裡面 ,
<td valign="top" class="t3t1" colspan="2">期間累計買賣超張數: <font color="red">-2</font></td>
但是又有下面這個版本,
差別在於網頁元素沒有將字體套用「字體顏色=紅」,
我們要的值 0 和中文還有標點符號被放在了一起,變成包在<td></td>裡面,
<td valign="top" class="t3t1" colspan="2">期間累計買賣超張數: 0</td>
既然這樣,就兩個版本的都篩選一次,
soup.find()
方法查找 <td>
標籤,其屬性必須滿足 class="t3t1"
以及 colspan="2"
。透過 text=lambda x: x and "期間累計買賣超張數" in x
的篩選條件,進一步找出 <td>
中包含關鍵字「期間累計買賣超張數」的文字。<td>
,直接使用相同屬性(class="t3t1" 和 colspan="2")
找第一個符合的 <td>
。<td>
,用 get_text(strip=True)
把裡面的文字提取出來,並且去除首尾的空格。summary_text
使用中文冒號 :
進行切割,後面的[-1]
會取得我們要的值。以下的程式碼可以直接一起包在 try 裡面,接續 DAY16 的程式碼:
try:
# 等待表格元素出現
table_element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "oMainTable"))
)
# 取得頁面內容
page_source = driver.page_source
soup = BeautifulSoup(page_source, 'html.parser')
# 取得買賣明細表資料
table = soup.find('table', {'id': 'oMainTable'})
if table is None:
print("找不到目標表格")
else:
data = []
for row in table.find_all('tr')[1:]: # 跳過表頭
cols = row.find_all('td')
if len(cols) == 5:
date = cols[0].get_text(strip=True)
buy = cols[1].get_text(strip=True)
sell = cols[2].get_text(strip=True)
total = cols[3].get_text(strip=True)
net = cols[4].get_text(strip=True)
data.append([date, buy, sell, total, net])
for item in data:
print(item)
# 取得「期間累計買賣超張數」的值
# 注意:此欄位可能內含 <font> 標籤,也可能直接是文字,因此使用 get_text() 可一次取得所有文字內容
summary_td = soup.find("td", {"class": "t3t1", "colspan": "2"}, text=lambda x: x and "期間累計買賣超張數" in x)
# 如果上述方式找不到,另一種方式是直接找第一個符合條件的<td>,因為頁面中只有一個此類元素
if summary_td is None:
summary_td = soup.find("td", {"class": "t3t1", "colspan": "2"})
if summary_td:
summary_text = summary_td.get_text(strip=True)
# 例如 summary_text 可能為 "期間累計買賣超張數:0" 或 "期間累計買賣超張數:-2"
net_total = summary_text.split(":")[-1]
print("期間累計買賣超張數:", net_total)
else:
print("找不到 期間累計買賣超張數 的欄位")
finally:
driver.quit()
這樣就會得到:
['2024/05/16', '6', '5', '11', '1']
['2024/05/15', '1', '4', '5', '-3']
期間累計買賣超張數: -2